//
// Created by 张朝辉 on 2023/10/21.
//

#include "dtm.h"
#include <iostream>
auto DTM::move_tape_head(mvd direction) -> bool {
    int pos = tape.getTapeHead();
    if(direction == mvd::LEFT && pos > 0){
        tape.setTapeHead(--pos);
        current_char = tape.getTapeContent()[pos];
        return true;
    }else if(direction == mvd::RIGHT && pos < tape.getTapeContent().length()-1){
        tape.setTapeHead(++pos);
        current_char = tape.getTapeContent()[pos];
        return true;
    }
    return false;
}

auto DTM::execute() -> void {
    std::cout<<"当前状态为："<<current_state<<"，当前字符："<<current_char;
    auto it = ruleBook.getRuleBook().find({current_state,current_char});
    if( it != ruleBook.getRuleBook().end()){
        std::cout<<"\t写入："<<it->second.overwrite_char;
        if(it->second.direction == mvd::RIGHT){
            std::cout<<"，右移，转移到状态"<<it->second.next_state<<std::endl;
        }else std::cout<<"，左移，转移到状态"<<it->second.next_state<<std::endl;
        write_char(it->second.overwrite_char);
        move_tape_head(it->second.direction);
        current_state = it->second.next_state;
        execute();
    }
}

auto DTM::write_char(char new_char) -> void {
    int pos = tape.getTapeHead();
    std::string content = tape.getTapeContent();
    content[pos] = new_char;
    tape.setTapeContent(content);
}

const std::string &DTM::getCurrentState() const {
    return current_state;
}

DTM::DTM(RuleBook ruleBook, Tape tape) : ruleBook(ruleBook), tape(tape){
    current_state = ruleBook.getStartState();
    current_char = tape.getTapeContent()[tape.getTapeHead()];
}
